package com.hsd.znsh.service.impl;

import com.hsd.znsh.entity.ManagerSecondManager;
import com.hsd.znsh.entity.User;
import com.hsd.znsh.enums.DeletedStatusEnum;
import com.hsd.znsh.enums.ResultEnum;
import com.hsd.znsh.enums.UserRoleEnum;
import com.hsd.znsh.exception.ZnshException;
import com.hsd.znsh.repository.ManagerSecondManagerRepository;
import com.hsd.znsh.repository.UserRepository;
import com.hsd.znsh.service.ManagerSecondManagerService;
import com.hsd.znsh.utils.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-05-02 18:55:31
 */
@Service
public class ManagerSecondManagerServiceImpl extends BaseServiceImpl implements ManagerSecondManagerService {

    @Autowired
    private ManagerSecondManagerRepository managerSecondManagerRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<User> getSecondManagerList(User user) {
        List<Integer> userIds=managerSecondManagerRepository.findSecondManagerIdListByManagerId(user.getId());
        return userRepository.findByIdInAndDeleted(userIds, DeletedStatusEnum.NOT_DELETED.getCode());
    }

    @Override
    public ManagerSecondManager addSecondManager(User user, String managerName) {
        if(managerName.equals(user.getUsername())) throw new ZnshException(ResultEnum.ADD_SELF_ERROR);
        User manager=userRepository.findByUsernameAndDeletedAndUserType(managerName,
                DeletedStatusEnum.NOT_DELETED.getCode(),
                UserRoleEnum.APP_MANAGER.getCode());
        if(manager==null) throw new ZnshException(ResultEnum.USERNAME_NOT_EXITS);
        if(managerSecondManagerRepository
                .findByManagerIdAndSecondManagerId(user.getId(),manager.getId())!=null){
            throw new ZnshException(ResultEnum.SECOND_MANAGER_EXITS);
        }
        ManagerSecondManager managerSecondManager=new ManagerSecondManager();
        managerSecondManager.setManagerId(user.getId());
        managerSecondManager.setSecondManagerId(manager.getId());
        return managerSecondManagerRepository.save(managerSecondManager);
    }

    @Override
    public void deleteSecondManager(User user, String managerName) {
        User manager=userRepository.findByUsernameAndDeletedAndUserType(managerName,
                DeletedStatusEnum.NOT_DELETED.getCode(),
                UserRoleEnum.APP_MANAGER.getCode());
        if(manager==null) throw new ZnshException(ResultEnum.USERNAME_NOT_EXITS);
        ManagerSecondManager managerSecondManager=managerSecondManagerRepository
                .findByManagerIdAndSecondManagerId(user.getId(),manager.getId());
        managerSecondManagerRepository.delete(managerSecondManager);
    }
}
